/*******************************************************************************

PooledRegions analysis_inputoutput_locations.do

2019.01.04 (DJ) Created

This do file uses agrovet surveys and store surveys to identify the locations
where the inputs and outputs come and go. 

*******************************************************************************/


// Pool Manyara and Kilimanjaro
	use "${analysis}/Manyara agrovet_shop_level.dta", clear
	rename av_village_id village_id
	merge m:1 village_id using "${analysis}/Manyara ViltoCities_dist.dta"
	keep if _merge==3
	keep av_ownerid av_shopid survey_region `agrovet_varlist' google_vil_* av_district av_ward av_village av_b1* av_b2* av_*_rev*
	tempfile manyara_avshop
	save `manyara_avshop'
	
	use "${analysis}/Kilimanjaro agrovet_shop_level.dta", clear
	gen survey_region = av_region
 
	keep av_ownerid av_shopid survey_region `agrovet_varlist' google_vil_* av_district av_ward av_village av_b1* av_b2* av_*_rev*
	append using `manyara_avshop'

	foreach var of varlist av_b11* av_b12* av_b13* av_b14*{
		replace `var' = strupper(`var')
		replace `var' = subinstr(`var', "_", " ", 1)
	}
	
	
	forvalues i=1/3{
		cap drop distributor`i'_loc
		gen distributor`i'_loc = "(" + av_b11_`i' + ") " + av_b12_`i' if !mi(av_b12_`i')
	}
	
	tab distributor1_loc, sort
	tab distributor2_loc, sort
	tab distributor3_loc, sort
	
	
	cap drop pc_seedfert_rev17_USD
	egen pc_seedfert_rev17_USD = pc(av_seedfert_rev17_USD), prop
	
	cap drop pc_seedfert_rev16_USD
	egen pc_seedfert_rev16_USD = pc(av_seedfert_rev16_USD), prop
	
	
	gsort -pc_seedfert_rev17_USD
	cap drop cumsum_seedfert_rev17_USD
	gen cumsum_seedfert_rev17_USD = sum(pc_seedfert_rev17_USD)
	
	br distributor1_loc av_seedfert_rev17_USD pc*17* cumsum*17*
	tab distributor1_loc if pc_seedfert_rev17_USD !=0, sort
	tab distributor1_loc if cumsum_seedfert_rev17_USD <=0.99, sort
	
	pause off
	preserve
		collapse (sum) pc_seedfert_rev17_USD, by(distributor1_loc)
		gsort -pc_seedfert_rev17_USD
		br
		pause
	restore
	
	
	gsort -pc_seedfert_rev16_USD
	cap drop cumsum_seedfert_rev16_USD
	gen cumsum_seedfert_rev16_USD = sum(pc_seedfert_rev16_USD)
	
	preserve
		collapse (sum) pc_seedfert_rev16_USD, by(distributor1_loc )
		gsort -pc_seedfert_rev16_USD
		br
		pause
	restore
